<template>
    <div class="module-content">
        <el-card class="!border-none cardArticle">
            <div class="detail-page-main-box-table">
                <div class="mb-4 module-header">
                    <h2>提现记录</h2>
                    <div>
                        <el-button type="primary" @click="openWithdrawDialog">
                            <el-icon><Money /></el-icon>
                            申请提现
                        </el-button>
                    </div>
                </div>
                <el-table :data="pager.lists" style="width: 100%" stripe>
                    <el-table-column label="序号" type="index" width="80" />
                    <!-- <el-table-column prop="sign_name" label="用户" width="120" /> -->
                    <el-table-column prop="bank_name" label="提现开户行" show-overflow-tooltip />
                    <el-table-column prop="bank_no" label="提现银行卡号" show-overflow-tooltip />
                    <el-table-column prop="username" label="提现开户名" show-overflow-tooltip />
                    <el-table-column prop="money" label="提现金额" show-overflow-tooltip />
                    <el-table-column prop="create_time" label="提现时间" width="180" />
                </el-table>
            </div>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" ref="paginationRef" />
            </div>
        </el-card>
        
        <!-- 提现申请弹窗 -->
        <el-dialog 
            v-model="withdrawDialogVisible" 
            title="申请提现" 
            width="500px"
            :before-close="handleDialogClose"
        >
            <el-form 
                ref="withdrawFormRef" 
                :model="withdrawForm" 
                :rules="withdrawRules" 
                label-width="120px"
                label-position="left"
            >
                <el-form-item label="可提现金额" class="balance-info">
                    <span class="balance-amount">¥{{ familyInfo.money || 0 }}</span>
                </el-form-item>
                
                <el-form-item label="提现金额" prop="money">
                    <el-input 
                        v-model.number="withdrawForm.money" 
                        placeholder="请输入提现金额"
                        type="number"
                        :min="0"
                        :max="familyInfo.money || 0"
                    >
                        <template #prefix>¥</template>
                    </el-input>
                </el-form-item>
                
                <el-form-item label="开户名" prop="username">
                    <el-input 
                        v-model="withdrawForm.username" 
                        placeholder="请输入银行卡开户名"
                        maxlength="20"
                        show-word-limit
                    />
                </el-form-item>
                
                <el-form-item label="银行卡号" prop="bank_no">
                    <el-input 
                        v-model="withdrawForm.bank_no" 
                        placeholder="请输入银行卡号"
                        maxlength="19"
                        show-word-limit
                    />
                </el-form-item>
                
                <el-form-item label="开户行" prop="bank_name">
                    <el-input 
                        v-model="withdrawForm.bank_name" 
                        placeholder="请输入银行卡开户行"
                        maxlength="50"
                        show-word-limit
                    />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose">取消</el-button>
                    <el-button 
                        type="primary" 
                        @click="submitWithdraw"
                        :loading="submitLoading"
                    >
                        提交申请
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Money } from '@element-plus/icons-vue'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback';
import { family_withdraw_list, familyDetail, family_withdraw } from '@/api/family'
import { useRoute } from 'vue-router'
const route = useRoute()



// 管理数据
const queryParams = ref({
    family_id: route.query.family_id
})
const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: family_withdraw_list,
    params: queryParams.value
})
// 获取数据列表
getLists()

// 获取家族详情
const familyInfo = ref<{
    [key: string]: any
}>({})
const getFamilyDetail = async () => {
    const res = await familyDetail({
        id: route.query.family_id
    })
    familyInfo.value = res
}

// 提现相关数据
const withdrawDialogVisible = ref(false)
const submitLoading = ref(false)
const withdrawFormRef = ref<FormInstance>()

// 提现表单数据
const withdrawForm = ref({
    money: '',
    username: '',
    bank_no: '',
    bank_name: ''
})

// 银行卡号校验
const validateCardNumber = (rule: any, value: string, callback: any) => {
    if (!value) {
        callback(new Error('请输入银行卡号'))
    } else if (!/^\d{16,19}$/.test(value)) {
        callback(new Error('银行卡号格式不正确，应为16-19位数字'))
    } else {
        callback()
    }
}

// 提现金额校验
const validateAmount = (rule: any, value: number, callback: any) => {
    console.log(value)
    if (!value) {
        callback(new Error('请输入提现金额'))
    } else if (value <= 0) {
        callback(new Error('提现金额必须大于0'))
    } else if (value > (familyInfo.value.money || 0)) {
        callback(new Error(`提现金额不能超过可提现金额¥${familyInfo.value.money || 0}`))
    } else {
        callback()
    }
}

// 表单校验规则
const withdrawRules: FormRules = {
    money: [
        { required: true, validator: validateAmount, trigger: 'blur' }
    ],
    username: [
        { required: true, message: '请输入银行卡开户名', trigger: 'blur' },
        { min: 2, max: 20, message: '开户名长度应为2-20个字符', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '开户名只能包含中文和英文字母', trigger: 'blur' }
    ],
    bank_no: [
        { required: true, validator: validateCardNumber, trigger: 'blur' }
    ],
    bank_name: [
        { required: true, message: '请输入银行卡开户行', trigger: 'blur' },
        { min: 2, max: 50, message: '开户行名称长度应为2-50个字符', trigger: 'blur' }
    ]
}

// 打开提现弹窗
const openWithdrawDialog = () => {
    if (!familyInfo.value.money || familyInfo.value.money <= 0) {
        ElMessage.warning('当前可提现金额为0，无法申请提现')
        return
    }
    withdrawDialogVisible.value = true
}

// 关闭弹窗
const handleDialogClose = () => {
    withdrawDialogVisible.value = false
    // 重置表单
    withdrawFormRef.value?.resetFields()
    withdrawForm.value = {
        money: '',
        username: '',
        bank_no: '',
        bank_name: ''
    }
}

// 提交提现申请
const submitWithdraw = async () => {
    if (!withdrawFormRef.value) return
    if (Number(withdrawForm.value.money) > Number(familyInfo.value.money)) {
        console.log(Number(withdrawForm.value.money), Number(familyInfo.value.money))
        ElMessage.warning('提现金额不能超过可提现金额')
        return false
    }
    try {
        // 表单校验
        await withdrawFormRef.value.validate()
        
        submitLoading.value = true
        
        // 这里应该调用提现API，暂时使用模拟
        await family_withdraw({
            family_id: route.query.family_id,
            money: withdrawForm.value.money,
            username: withdrawForm.value.username,
            bank_no: withdrawForm.value.bank_no,
            bank_name: withdrawForm.value.bank_name
        })
        // await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('提现申请提交成功，请等待审核')
        handleDialogClose()
        
        // 刷新家族信息
        await getFamilyDetail()
        
    } catch (error) {
        console.error('提现申请失败:', error)
    } finally {
        submitLoading.value = false
    }
}

onMounted(() => {
    getFamilyDetail()
})
</script>

<style scoped>
.module-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    overflow: hidden;
}

.module-header {
    padding: 20px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.module-header h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.filter-bar {
    display: flex;
    gap: 10px;
    align-items: center;
}

.table-container {
    padding: 0 20px 20px;
}

/* 提现弹窗样式 */
.balance-info {
    margin-bottom: 20px;
}

.balance-amount {
    font-size: 18px;
    font-weight: 600;
    color: #409eff;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
    font-weight: 500;
    color: #333;
}

:deep(.el-input__prefix) {
    color: #409eff;
    font-weight: 500;
}

:deep(.el-dialog__header) {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
    padding: 20px;
}

:deep(.el-dialog__footer) {
    padding: 10px 20px 20px;
    border-top: 1px solid #f0f0f0;
}
</style>